#!/usr/bin/env python
# coding: utf-8

import ConfigParser
import Queue
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
from wxbot import *


class MyWXBot(WXBot):
    def handle_msg_all(self, msg):

        conf = ConfigParser.ConfigParser()
        conf.read("img/config.conf")

        # 如果是修改群名称
        if msg['msg_type_id'] == 3 and msg['content']['type'] == 12 and msg['msg']['AppMsgType'] == 0 and u'修改群名为' in \
                msg['content']['data']:
            cfg = conf.get("switch", "keep_group")
            if cfg == '1':
                self.keepGroupName(msg)

        # 如果是添加好友消息
        if msg['msg_type_id'] == 37 and msg['content']['type'] == 37:
            # 自动接受好友添加消息
            cfg = conf.get("switch", "auto_confirm_add_friend")
            if cfg == '1':
                self.processAddFriend(msg)

        # 群消息 文本 群发
        elif msg['msg_type_id'] == 4 and msg['content']['type'] == 0:
            cfg = conf.get("switch", "group_send")
            if cfg == '1':
                self.groupSend(msg)
            cfg = conf.get("switch", "to_contacts")
            if cfg == '1':
                self.toContacts(msg)

        # 如果是加入群聊消息
        elif msg['msg_type_id'] == 3 and msg['content']['type'] == 12 and msg['msg']['AppMsgType'] == 0 and u'加入' in \
                msg['content']['data'] and u'群聊' in msg['content']['data']:
            cfg = conf.get("switch", "add_group_send_three")
            if cfg == '1':
                # 加入发送三条消息队列
                self.threeReplay(msg)

        # 如果是群里面发来的图片消息
        elif msg['msg_type_id'] == 3 and msg['content']['type'] == 3:
            # 群消息 图片 自动回复已收到群消息
            cfg = conf.get("switch", "group_img_replay")
            if cfg == '1':
                self.groupImgSend(msg)

        # 如果是联系人消息，并且是图片的话
        elif msg['msg_type_id'] == 4 and msg['content']['type'] == 3:
            cfg = conf.get("switch", "single_img_replay")
            if cfg == '1':
                self.singleSendImgReply(msg)
        # 如果是未知帐号消息，并且是图片的话
        elif msg['msg_type_id'] == 99 and msg['content']['type'] == 3:
            cfg = conf.get("switch", "single_img_replay")
            if cfg == '1':
                self.singleSendImgReply(msg)
        else:
            logging.info(str(json.dumps(msg)))

        # 如果出现修改用户列表
        if 'ModContactList' in msg['r']:
            if len(msg['r']['ModContactList']) > 0 and 'MemberList' in msg['r']['ModContactList'][0]:
                # 同步用户信息
                self.syncUsers(msg)

    # 个人发送图片后回复
    def singleSendImgReply(self, msg):
        file_object = open(unicode(cur_file_dir() + "/img/个人发截图后回复消息.txt", "utf8"))
        try:
            text1 = file_object.read()
        finally:
            file_object.close()
        userId = msg['user']['id']
        # 如果发送对象是群，不发送
        if userId.startswith("@@"):
            logging.info("个人发送图片后回复，群")
        else:
            self.send_msg_by_uid(text1, userId)

    def keepGroupName(self, msg):
        oldName = msg['user']['name']
        newName = msg['r']['ModContactList'][0]['NickName']

        # 如果新主题不等于旧主题，进行修改群昵称
        if oldName != newName:
            # 如果群的名称都不为unknown
            if oldName != 'unknown' and newName != 'unknown':
                self.updRoomName(msg['r']['ModContactList'][0]['UserName'], msg['user']['name'])

    # 自动接受好友添加消息
    def processAddFriend(self, msg):
        # 添加好友
        self.verifyuser(msg['content']['data']['UserName'], msg['content']['data']['Ticket'])
        conf = ConfigParser.ConfigParser()
        conf.read("img/config.conf")
        cfg = conf.get("switch", "auto_confirm_send_three")
        if cfg == '1':
            # 发送消息
            file_object = open(cur_file_dir() + '/img/gr_txt1.txt')
            try:
                text1 = file_object.read()
            finally:
                file_object.close()

            file_object = open(cur_file_dir() + '/img/gr_txt2.txt')
            try:
                text2 = file_object.read()
            finally:
                file_object.close()
            self.send_msg_by_uid(text1, msg['content']['data']['UserName'])
            self.send_msg_by_uid(text2, msg['content']['data']['UserName'])
            self.send_img_msg_by_uid("img/gr_subs.jpg", msg['content']['data']['UserName'])

    # 使用groupsend群发文本消息
    def groupSend(self, msg):
        content = msg['content']['data']
        # print content
        content = content.split(":", 1)
        # print json.dumps(content)
        if content[0] == 'groupsend':
            content[1].replace(u'\r\n', u" ")
            line = content[1].split("<br/>")
            content[1] = u"\r\n".join(line)
            timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            with open(os.path.join(self.temp_pwd, 'grouplist-' + timestr + '-group_list.json'), 'w') as f:
                f.write(json.dumps(self.group_list))
            f = open(self.temp_pwd + '/groupsendlist-' + timestr + '-groupsend.txt', 'a')
            for k, v in enumerate(self.group_list):
                # 给所有群发消息
                dic = self.send_msg_by_uid(content[1], v['UserName'])
                f.write(v['UserName'] + '   ' + json.dumps(dic) + '\r\n')
                f.flush()
                time.sleep(5)
            f.close()

    # 给所有联系人发送消息
    def toContacts(self, msg):
        content = msg['content']['data']
        # print json.dumps(content)

        if content == 'tocontacts':
            # 发送消息

            file_object = open(self.data_dir + '/to_contacts_txt1.txt')
            try:
                text1 = file_object.read()
            finally:
                file_object.close()
            length = len(self.contact_list)
            logging.info("共" + str(length) + "个联系人:")
            for k, v in enumerate(self.contact_list):
                try:
                    sendTxt = self.send_msg_by_uid(text1, v['UserName'])
                    sendImg = self.send_img_msg_by_uid(self.data_dir + '/to_contacts.jpg', v['UserName'])
                    logging.info(
                        "给" + v["NickName"] + "的消息,txt:" + str(sendTxt) + ",img:" + str(sendImg) + ",消息发送到" + str(
                            k + 1) + "个,还剩" + str(length - k - 1) + "个未发")
                except:
                    logging.error("给" + v["NickName"] + "的消息发送出现异常")
                time.sleep(8)

    # 同步用户信息
    def syncUsers(self, msg):
        for index, value in enumerate(msg['r']['ModContactList'][0]['MemberList']):
            # print json.dumps( value )
            if 'NickName' in value:
                # if newuser.UserName not in self.account_info['group_member']:
                # print value['UserName']+"  "+value['NickName']
                self.new_group_member[value['UserName']] = value['NickName']

    # 新人进群的三条回复
    def threeReplay(self, msg):

        # 新进群的用户发欢迎信息昵称是从字符串正则匹配出的，存在临时变量中
        filename = os.path.join(self.temp_pwd, msg['user']['id'].replace("@", "") + ".txt")
        # print filename
        if not os.path.isfile(filename):
            fp = open(cur_file_dir() + "/" + filename, "w+")
            fp.write("test")
            fp.close()
        nicknames = re.findall(u'"(.+?)"', msg['content']['data'])
        nickname = nicknames[0]

        filename_first = os.path.join(self.temp_pwd, msg['user']['id'].replace("@", "") + "_first.txt")
        if not os.path.isfile(filename_first):
            fp = open(cur_file_dir() + "/" + filename_first, "w+")
            fp.write("test")
            fp.close()
            isfirstmsg = True
        else:
            isfirstmsg = False
        _last = os.path.getmtime(filename)
        _now = time.time()
        print _last
        print _now
        mistake = _now - _last
        if mistake > 45 or isfirstmsg == True:
            os.remove(filename)
            file_object = open(cur_file_dir() + '/img/txt1.txt')
            try:
                text1 = file_object.read()
            finally:
                file_object.close()

            file_object = open(cur_file_dir() + '/img/txt2.txt')
            try:
                text2 = file_object.read()
            finally:
                file_object.close()
            self.send_msg_by_uid(text1, msg['user']['id'])
            self.send_msg_by_uid(text2, msg['user']['id'])
            self.send_img_msg_by_uid(cur_file_dir() + "/img/subs.jpg", msg['user']['id'])

    groupDic = {};

    def groupImgSend(self, msg):
        nickname = msg['content']['user']['name']
        if nickname == 'unknown':
            if msg['content']['user']['id'] in self.account_info['group_member'].keys():
                nickname = self.account_info['group_member'][msg['content']['user']['id']]['info']['NickName']
                print 'nickname1:'
            if msg['content']['user']['id'] in self.new_group_member.keys():
                nickname = self.new_group_member[msg['content']['user']['id']]
                print 'nickname2:'
        dr = re.compile(r'<[^>]+>', re.S)
        nickname = dr.sub('', nickname)
        dr = re.compile(r'<[^>]+>', re.S)
        nickname = dr.sub('', nickname)
        adminname = [u'管理员', u'娜娜（统一拉电影群）', u'Vivian', u'Lee']
        groupId = msg['user']['id']
        # 如果字典中没有该群的队列
        if self.groupDic.has_key(groupId) == False:
            # 新建一个队列
            myqueue = Queue.Queue(0)
            self.groupDic[groupId] = myqueue;

        # 如果昵称不在规定管理员里，加入到该群的队列中区
        if nickname not in adminname:
            self.groupDic[groupId].put(nickname)

    # 初始化30秒检测器
    def initSchedule(self):
        # 启动一个30秒检查一次的任务，用于进行队列清空，并发送图文消息
        job_thread = threading.Thread(target=self.job_func)
        job_thread.start()

    def job_func(self):
        schedule.every(30).seconds.do(self.job)
        while True:
            schedule.run_pending()
            time.sleep(10)

    def job(self):
        # 遍历所有的群，拿出他们的消息队列
        for k in self.groupDic:
            que = self.groupDic[k];
            # 如果该群下的队列不为空
            if que.qsize() > 0:
                # 要发送的内容
                pictext = ""
                file_object = open(cur_file_dir() + '/img/txtpic.txt')
                try:
                    pictext = file_object.read()
                finally:
                    file_object.close()
                content = ""
                # 去除队列里的所有昵称
                while que.qsize() > 0:
                    # 取出昵称
                    content += "@" + que.get().encode("utf-8")
                # 往群内发送消息
                self.send_msg_by_uid(content + pictext, k)


def main():
    # 机器人唯一ID
    uid = sys.argv[1];
    bot = MyWXBot()
    bot.DEBUG = True
    bot.uid = uid;
    bot.conf['qr'] = 'png'
    bot.initSchedule()
    bot.is_big_contact = True
    bot.run(isOpenImg=False)


if __name__ == '__main__':
    main()
